﻿using Autofac.Integration.Web.Forms;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Timesheet.Service;
using Timesheet.Common;
using Timesheet.Domain;

namespace Timesheet.WebForm.Account
{
    public partial class Login : Page
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(Login));
        
        public IUserService UserService { get; set;} //dependency injection  NInject , ServiceStack , Autofac 

        protected void Page_Load(object sender, EventArgs e)
        {
            //RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
            if (!IsPostBack)
            {
                // *** Always force a signout when the page loads first
                FormsAuthentication.SignOut();
                if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
                {
                    HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                    if (!string.IsNullOrEmpty(cookie.Value))
                    {
                        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
                        string[] data = ticket.UserData.Split('|');
                        if (data.Length > 0)
                        {
                            String encryptPassword = PasswordUtils.getHashPassword(data[1]);
                            if (UserService.CheckAccountLogin(data[0], encryptPassword))
                            {
                                User info = UserService.GetByUsername(data[0]);
                                if(info != null)
                                {
                                    Session["Username"] = info.Username;
                                    Session["UserId"] = info.Id;
                                    Session["User"] = info;
                                    Session["userrole"] = info.Manager ? "3" : info.Coordinator ? "2" : info.TeamLead ? "1" : "0";
                                }
                                //info.login_time = DateTime.Now;
                                //UserService.Update(info);

                                string ticketString = FormsAuthentication.Encrypt(ticket);
                                cookie.Expires = DateTime.Now.AddDays(10);
                                Response.Cookies.Clear();
                                Response.Cookies.Add(cookie);
                                string url = HttpUtility.UrlDecode(Request.QueryString["ReturnUrl"]);
                                if (!string.IsNullOrEmpty(url))
                                {
                                    Response.Redirect(url);
                                }
                                else
                                {
                                    Response.Redirect("~/Home.aspx");
                                }
                            }
                        }
                    }
                }
            }
        }

        protected void LoginUser_LoggedIn(object sender, EventArgs e)
        {

            //ASPxTextBox username = (ASPxTextBox)LoginUser.FindControl("UserName");
            //UserInfo info = userInfoService.GetByUsername(username.Text);

            //Session["Username"] = username.Text;
            //Session["UserId"] = info.Id;
        }


        protected void ASPxBtnLogin_Click(object sender, EventArgs e)
        {

            String encryptPassword = PasswordUtils.getHashPassword(ASPxTxtPassword.Text);
            if (UserService.CheckAccountLogin(ASPxTxtUserName.Text, encryptPassword))
            {
                User info = UserService.GetByUsername(ASPxTxtUserName.Text);
                if(info == null) return;
                Session["Username"] = info.Username;
                Session["UserId"] = info.Id;
                Session["User"] = info;
                Session["userrole"] = info.Manager ? "3" : info.Coordinator ? "2" : info.TeamLead ? "1" : "0";
                //info.login_time = DateTime.Now;
                //UserService.Update(info);

                // *** Created custom ticket so we can attach a custom data
                //     item. In this case we store username|userpk
                //     which is split out in the Master Page to provide Username and UserPk props
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                        ASPxTxtUserName.Text,
                        DateTime.Now,
                        DateTime.Now.AddDays(10),
                        true,
                         String.Format("{0}|{1}", ASPxTxtUserName.Text, ASPxTxtPassword.Text));

                string ticketString = FormsAuthentication.Encrypt(ticket);

                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketString);

                if (ASPxChkRememberMe.Checked)
                    cookie.Expires = DateTime.Now.AddDays(10);
                Response.Cookies.Add(cookie);
                string url = HttpUtility.UrlDecode(Request.QueryString["ReturnUrl"]);
                if (!string.IsNullOrEmpty(url))
                {
                    Response.Redirect(url);
                }
                else
                {
                    Response.Redirect("~/Home.aspx");
                }
            }
            else
            {
                ASPxLblError.Visible = true;
            }
        }

        protected void ASPxTxtUserName_TextChanged(object sender,EventArgs e)
        {

        }


    }
    
}